'use strict';
import React from "react";
import {
    View,
    StyleSheet,
    Text,
    TextInputComponent,
    TextInput,
    TouchableOpacityComponent,
    TouchableOpacity,
    KeyboardAvoidingView
} from "react-native";
import Container from "../../component/common/Container";
import NavigationBar from "../../component/navigation/NavigationBar";
import ListView from "../../component/list/ListView";
import ImageView from "../../component/common/ImageView";
import { diffTime } from "../../util/Tool";
import Button from "../../component/common/Button";
import {inject, observer} from "mobx-react";

@inject('taskStore')
@observer
class CommentList extends React.Component {

    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.topic_id = this.params.topic_id;
        this.reply_module = this.params.reply_module;
        this.state = { data: [], replyCount: 0 };
        this.page = 1;
        this.limit = 10;
        this.replyContent = '';
        this.replyType = 'topic';
        this.replyParam = {};
    }

    componentDidMount() {
        this.requestCommentList();
    }

    componentWillUnmount() {
        this.params.onCallBack && this.params.onCallBack();
    }

    requestCommentList = async () => {
        const data = {
            topic_id: this.topic_id,
            reply_module: this.reply_module,
            type: 'main',
            page: this.page,
            limit: this.limit,
            reply_type: 'topic',
        };
        const result = await Services.post(ServicesApi.COMMENT_LIST, data);
        // console.log('评论列表返回------------->', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let dataSource = [];
            if (Array.isArray(result.data)) {
                if (data.page === 1) {
                    dataSource = result.data;
                } else {
                    let temp = this.state.data;
                    dataSource = temp.concat(result.data);
                }
            }
            this.setState({ data: dataSource, replyCount: result.count });
        }
        this._listRef && this._listRef.stopRefresh();
        this._listRef && this._listRef.stopEndReached({ allLoad: result.data.length < this.limit }); // 是否加载完毕需要自行判断
    };

    _onReplyContentChange = (text) => {
        this.replyContent = text;

    };

    //input失去焦点时调用的方法
    _onInputBlur = () => {
        this.replyType = 'topic';
    };

    _onPressSend = async () => {
        const {taskStore} = this.props;
        if (!this.replyContent) {
            ToastManager.show('回复内容不能为空哦~');
            return;
        }
        // console.log('发送', this.replyContent);
        const data = {
            topic_id: this.topic_id,
            reply_content: this.replyContent,
            create_user: global.secretKey,
            reply_type: this.replyType,
            reply_module: this.reply_module,
        };
        const result = await Services.post(ServicesApi.REPLY_SAVE, data);
        // console.log('评论回复返回------------>', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.show('评论成功!');
            this.inputRef.clear();
            this.inputRef.blur();
            this.replyContent = '';
            this._onRefresh();
            await taskStore.saveTask('topic')
        } else {
            ToastManager.show(result.dec || 'error');
        }
    };

    _onPressReply = (item) => {
        // console.log('item------------->', item);
        RouterHelper.navigate('回复', 'ReplyList', { reply_id: item.reply_id, reply_module: this.reply_module, topic_id: this.topic_id });
    };

    renderBottomComment = (props) => {
        return (
            <KeyboardAvoidingView
                behavior={__IOS__ ? 'position' : 'height'} >
                <View style={styles.bottomContentView}>
                    <TextInput
                        placeholder={'回复'}
                        maxLength={80}
                        style={styles.bottomInput}
                        ref={(v) => {
                            this.inputRef = v
                        }}
                        numberOfLines={2}
                        // onBlur={this._onInputBlur}
                        onChangeText={this._onReplyContentChange}
                    />
                    <Button
                        title={'发送'}
                        style={styles.bottomButton}
                        titleStyle={styles.bottomButtonTitle}
                        onPress={this._onPressSend}
                    />
                </View>
            </KeyboardAvoidingView>
        )
    };

    renderItem = (info) => {
        const { item, index } = info;
        return (
            <View style={styles.itemView}>
                <View style={styles.itemUserView}>
                    <ImageView
                        resizeMode={'cover'}
                        style={styles.itemUserHead}
                        source={item.user_img ? { uri: item.user_img } : Images.icon_default_avatar}
                    />
                    <Text style={styles.itemUserName}>{item.user_nickname}</Text>
                </View>
                <Text style={styles.itemUserContent}>{item.reply_content}</Text>
                <View style={styles.itemBottom}>
                    <Text style={styles.itemTime}>{diffTime(item.create_time)}</Text>
                    <TouchableOpacity onPress={() => this._onPressReply(item)}>

                        <View style={styles.replyRow}>
                            <ImageView
                                style={styles.bottomIcon}
                                source={Images.icon_comment_msg}
                            />
                            <Text style={styles.replyCount}>{item.replyChildren.length === 0 ? '' : item.replyChildren.length}</Text>
                        </View>

                    </TouchableOpacity>
                </View>
            </View>
        )
    };

    renderSep = () => {
        return (
            <View style={styles.sep} />
        )
    };

    _onRefresh = () => {
        this.page = 1;
        this.requestCommentList();
    };

    _onEndReached = () => {
        this.page++;
        this.requestCommentList();
    };

    _captureRef = (v) => {
        this._listRef = v
    };

    _keyExtractor = (item, index) => {
        return `${index}`
    };

    render() {
        const pageTitle = this.params.pageTitle || '评论';
        const { data, replyCount } = this.state;
        return (
            <Container>
                <NavigationBar
                    title={pageTitle}
                />
                <View style={styles.headView}>
                    <Text style={styles.headText}>{`评论：${replyCount}`}</Text>
                    <Text
                        onPress={() => {
                            RouterHelper.goBack();
                        }}
                        style={styles.headBackText}>返回文章</Text>
                </View>
                <ListView
                    data={data}
                    initialRefresh={false}
                    enableRefresh={true}
                    enableLoadMore={true}
                    style={styles.lv}
                    ref={this._captureRef}
                    onRefresh={this._onRefresh}
                    renderItem={this.renderItem}
                    keyExtractor={this._keyExtractor}
                    onEndReached={this._onEndReached}
                    ItemSeparatorComponent={this.renderSep}
                />
                <this.renderBottomComment />
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    headView: {
        paddingVertical: 10,
        paddingHorizontal: 15,
        flexDirection: 'row',
        justifyContent: 'space-between',

    },
    headText: {
        fontSize: FontSize(12),
        color: "#a3a3a3",
    },
    headBackText: {
        fontSize: FontSize(14),
        color: "#f5a623",
    },
    lv: {
        marginBottom: 20,
    },
    itemView: {
        marginVertical: 12,
        marginHorizontal: 15,
    },
    itemUserView: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    itemUserHead: {
        width: 30,
        height: 30,
        borderRadius: 30 / 2,
    },
    itemUserName: {
        marginLeft: 9,
        fontSize: FontSize(14),
        color: "#7e7d7d",
    },
    itemUserContent: {
        marginTop: 4,
        marginLeft: 39,
        fontSize: FontSize(16),
        color: "#646464",
        fontFamily: "PingFangSC-Regular",
        lineHeight: 20,
    },
    itemBottom: {
        marginTop: 7,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginLeft: 39,
    },
    itemTime: {
        fontSize: FontSize(12),
        color: "#a3a3a3",
    },
    replyRow: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    bottomIcon: {
        width: 16,
        height: 16,
    },
    replyCount: {
        color: '#333',
        marginLeft: 5,
        fontSize: FontSize(12),
    },
    bottomContentView: {
        flexDirection: 'row',
        alignItems: 'center',
        width: '100%',
        backgroundColor: '#fff',
        paddingVertical: 7,
        paddingHorizontal: 10,
        borderTopColor: '#dbdbdb',
        borderTopWidth: StyleSheet.hairlineWidth,
    },
    bottomInput: {
        fontSize: 13,
        flex: 1,
        marginRight: 16,
        color: '#333',
        borderRadius: 8,
        backgroundColor: "#f4f4f4",
        paddingVertical: 5,
        paddingHorizontal: 16,
    },
    bottomButton: {
        paddingHorizontal: 13,
        paddingVertical: 7,
        borderRadius: 5,
        backgroundColor: "#fdac5d"
    },
    bottomButtonTitle: {
        fontSize: FontSize(14),
        color: "#ffffff",
    },
    sep: {
        height: StyleSheet.hairlineWidth,
        backgroundColor: '#dbdbdb',
    }
});
export default CommentList